//go:build mage

package main

import (
	"fmt"
	"os"

	"github.com/magefile/mage/mg"
	"github.com/magefile/mage/sh"
)

// Default 设置默认目标
var Default = All

// All 构建所有目标
func All() error {
	mg.Deps(BuildCPP)
	return BuildGo()
}

// BuildCPP 编译 C++ 代码并生成动态库
func BuildCPP() error {
	// 编译 calculator.cpp 为目标文件
	fmt.Println("Compiling calculator.cpp...")
	err := sh.Run("g++", "-fPIC", "-Wall", "-std=c++11", "-c", "calculator.cpp", "-o", "calculator.o")
	if err != nil {
		return err
	}

	// 生成动态库
	fmt.Println("Generating dynamic library...")
	return sh.Run("g++", "-shared", "-o", "libcalculator.dylib", "calculator.o")
}

// BuildGo 构建 Go 程序
func BuildGo() error {
	fmt.Println("Building Go program...")
	return sh.Run("go", "build", "-o", "calculator", "main.go")
}

// Clean 清理编译产物
func Clean() error {
	fmt.Println("Cleaning build artifacts...")
	files := []string{"calculator.o", "libcalculator.dylib", "calculator"}
	for _, file := range files {
		if err := os.Remove(file); err != nil && !os.IsNotExist(err) {
			return err
		}
	}
	return nil
}
